from PySide6.QtWidgets import QDialog, QMessageBox
from PySide6.QtCore import QTimer, Signal, QCoreApplication
from ui.stage_ui import Ui_StageSettingsDialog
from drivers.motor_controller import MotorController
# from drivers.fake_motor_controller import FakeMotorController as MotorController
from utils.config_manager import ConfigManager

class StageController(QDialog):
    settings_applied = Signal()  # 添加信号
    def _load_to_ui(self):
        """将 config 中的值填入 UI 表单"""
        for axis in [0, 1]:
            prefix = 'x' if axis == 0 else 'y'
            settings = self.axis_settings[axis]
            getattr(self.ui, f"lineEdit_{prefix}_start").setValue(float(settings['start']))
            getattr(self.ui, f"lineEdit_{prefix}_end").setValue(float(settings['end']))
            getattr(self.ui, f"lineEdit_{prefix}_max_speed").setValue(float(settings['vmax']))
            getattr(self.ui, f"lineEdit_{prefix}_max_acc").setValue(float(settings['acc']))
            getattr(self.ui, f"lineEdit_{prefix}_step").setValue(float(settings['step']))
            getattr(self.ui, f"lineEdit_{prefix}_move").setValue(0.00)
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_StageSettingsDialog()
        self.ui.setupUi(self)

        self.motor = MotorController()
        self.motor.connect()

        self.config = ConfigManager()
        self.axis_settings = {
            0: self.config.get_stage_axis_config('x'),
            1: self.config.get_stage_axis_config('y')
        }

        self._load_to_ui()
        self._apply_speed_to_motor()

        self._bind_signals()
        self._start_position_timer()
        self.motor.debug_print_conversion()
    
    def showEvent(self, event):
        # 每次打开窗口都重新加载配置
        self.axis_settings = {
            0: self.config.get_stage_axis_config('x'),
            1: self.config.get_stage_axis_config('y')
        }
        self._load_to_ui()
        super().showEvent(event)

    def _bind_signals(self):
        self.ui.btn_x_set_start.clicked.connect(lambda: self._set_current_to_field(0, 'start'))
        self.ui.btn_x_set_end.clicked.connect(lambda: self._set_current_to_field(0, 'end'))
        self.ui.btn_x_move.clicked.connect(lambda: self._move_to_target(0))
        self.ui.btn_x_home.clicked.connect(lambda: self.motor.home_axis(0))
        self.ui.btn_x_manual_home.clicked.connect(lambda: self.motor.set_position(0, 0))
        self.ui.btn_x_move_pos.pressed.connect(lambda: self._start_continuous_move(0, +1))
        self.ui.btn_x_move_neg.pressed.connect(lambda: self._start_continuous_move(0, -1))
        self.ui.btn_x_move_pos.released.connect(lambda: self.motor.stop(0))
        self.ui.btn_x_move_neg.released.connect(lambda: self.motor.stop(0))
        self.ui.btn_x_stop.clicked.connect(lambda: self.motor.stop(0))
        self.ui.btn_x_emergency_stop.clicked.connect(lambda: self.motor.halt_all())

        self.ui.btn_y_set_start.clicked.connect(lambda: self._set_current_to_field(1, 'start'))
        self.ui.btn_y_set_end.clicked.connect(lambda: self._set_current_to_field(1, 'end'))
        self.ui.btn_y_move.clicked.connect(lambda: self._move_to_target(1))
        self.ui.btn_y_home.clicked.connect(lambda: self.motor.home_axis(1))
        self.ui.btn_y_manual_home.clicked.connect(lambda: self.motor.set_position(1, 0))
        self.ui.btn_y_move_pos.pressed.connect(lambda: self._start_continuous_move(1, +1))
        self.ui.btn_y_move_neg.pressed.connect(lambda: self._start_continuous_move(1, -1))
        self.ui.btn_y_move_pos.released.connect(lambda: self.motor.stop(1))
        self.ui.btn_y_move_neg.released.connect(lambda: self.motor.stop(1))
        self.ui.btn_y_stop.clicked.connect(lambda: self.motor.stop(1))
        self.ui.btn_y_emergency_stop.clicked.connect(lambda: self.motor.halt_all())

        self.ui.btn_apply.clicked.connect(self._apply_settings)
        self.ui.btn_cancel.clicked.connect(self.reject)

    def _start_position_timer(self):
        self.timer = QTimer(self)
        self.timer.timeout.connect(self._update_positions)
        self.timer.start(500)

    def _update_positions(self):
        self.ui.label_x_position_value.setText(f"{self.motor.get_position(0):.3f}")
        self.ui.label_y_position_value.setText(f"{self.motor.get_position(1):.3f}")

    def _set_current_to_field(self, axis, field):
        pos = self.motor.get_position(axis)
        target = getattr(self.ui, f"lineEdit_{'x' if axis == 0 else 'y'}_{field}")
        target.setValue(pos)
        # target.setText(f"{pos:.3f}")

    def _move_to_target(self, axis):
        input_field = getattr(self.ui, f"lineEdit_{'x' if axis == 0 else 'y'}_move")
        try:
            value = float(input_field.text())
            if not -12.5 <= value <= 12.5:
                raise ValueError(QCoreApplication.translate("StageController","超出范围"))
            self.motor.move_to(axis, value)
        except Exception as e:
            QMessageBox.warning(self, QCoreApplication.translate("StageController","错误"), QCoreApplication.translate("StageController","无效的移动位置: {e}").format(e=e))

    def _apply_speed_to_motor(self):
        for axis in [0, 1]:
            s = self.axis_settings[axis]
            self.motor.set_speed(axis, s['acc'], s['acc'], s['vmax'])

    def _apply_settings(self):
        for axis in [0, 1]:
            prefix = 'x' if axis == 0 else 'y'
            try:
                vmax = getattr(self.ui, f"lineEdit_{prefix}_max_speed").value()
                acc = getattr(self.ui, f"lineEdit_{prefix}_max_acc").value()
                step = getattr(self.ui, f"lineEdit_{prefix}_step").value()
                start = getattr(self.ui, f"lineEdit_{prefix}_start").value()
                end = getattr(self.ui, f"lineEdit_{prefix}_end").value()

                self.axis_settings[axis].update({
                    'vmax': vmax, 'acc': acc, 'step': step,
                    'start': start, 'end': end
                })
                self.motor.set_speed(axis, acc, acc, vmax)
                self.config.set_stage_axis_config(prefix, self.axis_settings[axis])
            except Exception as e:
                QMessageBox.warning(self, QCoreApplication.translate("StageController","错误"), QCoreApplication.translate("StageController","{prefix.upper()}轴设置无效: {e}").format(e=e))
        QMessageBox.information(self, QCoreApplication.translate("StageController","成功"), QCoreApplication.translate("StageController","设置已应用并更新到设备"))
        self.settings_applied.emit()  # 应用后发出信号
        self.accept()  # 自动关闭窗口

    def _start_continuous_move(self, axis, direction):
        self.motor.move_by(axis, direction)